package com.sz.wallet_demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sz.wallet_demo.config.CurrContextHolder;
import com.sz.wallet_demo.mapper.UserMapper;
import com.sz.wallet_demo.model.User;
import com.sz.wallet_demo.result.Result;
import com.sz.wallet_demo.utils.RedisCache;
import com.sz.wallet_demo.vo.CurrVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Ts-SuSu
 * @date 2023/9/2 7:42
 * @Description 用户管理
 * 1.登录接口，登录成功将用户信息存入ThreadLocal中*
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    private UserMapper userMapper;
    private RedisCache redisCache;

    public UserController(UserMapper userMapper, RedisCache redisCache) {
        this.userMapper = userMapper;
        this.redisCache = redisCache;
    }

    @ApiOperation("用户管理-登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String")
    })
    @PostMapping("/login")
    public Result login(@RequestParam String username) {
        //省略密码登录
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (Objects.isNull(user)) {
            return Result.fail("该用户不存在");
        }
        String token = UUID.randomUUID().toString();
        CurrVo currVo = new CurrVo();
        currVo.setUser(user);
        currVo.setToken(token);
        CurrContextHolder.setUser(currVo);
        redisCache.set("auth:" + token, user, 1800, TimeUnit.SECONDS);
        return Result.success(currVo, "登录成功");
    }
}
